package at.theengine.android.gs4android;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import at.theengine.android.botstorage.*;

public class Gs4Android extends Activity {
	
	private GSDataAdapter gsd;
	private static final String tag = "GS4ANDROID";
	public static final String PREFS_NAME = "GS4ANDROID_SETTINGS";
	
	private SharedPreferences settings;
	
	private ListView lstBuckets;
	private TextView tvBucketPath;
	private ProgressDialog pdlg;
	
	private Gs4Android ctx;
	
	private String[] buckets;
	
	//menu item ids
	private static final int MENU_RELOAD = Menu.FIRST;
	private static final int MENU_SETTINGS = Menu.FIRST + 1;
	private static final int MENU_NEW_BUCKET = Menu.FIRST + 2;
	private static final int MENU_HELP = Menu.FIRST + 3;
	private static final int MENU_INFO = Menu.FIRST + 4;
	private static final int MENU_EXIT = Menu.FIRST + 5;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ctx = this;
        lstBuckets = (ListView) this.findViewById(R.id.lstBuckets);
        tvBucketPath = (TextView) this.findViewById(R.id.tvBucketPath);
        tvBucketPath.setText("/HOME");
        
        loadBuckets();
    }
    
    private boolean refreshGsd(){
    	settings = getSharedPreferences(PREFS_NAME, 0);
    	String key = settings.getString("gsKey", "");
    	String secret = settings.getString("gsSecret", "");
    	
    	if(key.equals("") || secret.equals("")){
    		Toast.makeText(this, "Google Storage Key and Secret not set!", Toast.LENGTH_LONG).show();
    		return false;
    	}
    	
    	if(gsd == null){
    		gsd = new GSDataAdapter(key,secret);
    	}
    	return true;
    }
    
    private void loadBuckets(){
    	if(!refreshGsd()){ return; } 
    	
    	pdlg = ProgressDialog.show(this,"", "loading buckets...", true); 
    	pdlg.show();
    	
    	class BucketLoader extends AsyncTask<Void, String, Void> {
    		private boolean success = false;
    		private String error;
    		
    		@Override
    		protected Void doInBackground(Void... unused) {
	    		try {
	    			buckets = gsd.getBucketNames();
	    			success = true;
	    		} catch (BotStorageException e) {
	    			success = false;
	    			gsd = null;
	    			error = e.getMessage();
				}
    			return(null);
    		}

    		@Override
    		protected void onPostExecute(Void unused) {
    			if(success){
    				lstBuckets.setAdapter(new ArrayAdapter<String>(ctx,R.layout.bucket_listitem,R.id.litBucketText,buckets));
    				
    				lstBuckets.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
							String bucket = buckets[(int) id];
							Intent intentBrowser = new Intent(Gs4Android.this, ObjectBrowser.class);
					        ArrayList<String> params = new ArrayList<String>();
					        params.add(bucket);
					        intentBrowser.putStringArrayListExtra("PATH", params);
					        Gs4Android.this.startActivityForResult(intentBrowser,2);
						}
    		        });
    				
    				tvBucketPath.setText("/HOME");
    			} else {
    				tvBucketPath.setText("Error: " + error);
    			}
    	    	
    			pdlg.dismiss();
    		}
    	}
    	
    	new BucketLoader().execute();
    }
    
    //MENU
    /* Creates the menu items */
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, MENU_RELOAD, 0, "Refresh");
    	menu.add(0, MENU_SETTINGS, 0, "Settings");
    	menu.add(0, MENU_NEW_BUCKET, 0, "new Bucket");
    	menu.add(0, MENU_HELP, 0, "Help");
    	menu.add(0, MENU_INFO, 0, "Info");
        menu.add(0, MENU_EXIT, 0, "Quit");
        return true;
    }

    /* Handles item selections */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_RELOAD:
            loadBuckets();
            return true;
        case MENU_SETTINGS:
        	Intent intentSettings = new Intent(Gs4Android.this, Settings.class);
	        Gs4Android.this.startActivityForResult(intentSettings,0);
	        return true;
        case MENU_EXIT:
            this.finish();
            return true;
        }
        return false;
    }
}